{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 决策树 概述\n",
    "决策树（Decision Tree）算法主要用来处理分类问题，是最经常使用的数据挖掘算法之一。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 决策树 原理\n",
    "构造决策树的方法：\n",
    "createBranch递归调用\n",
    "```\n",
    "createBranch()\n",
    "    检测数据集中的所有数据的分类标签是否相同:\n",
    "        If so return 类标签\n",
    "        Else:\n",
    "            寻找划分数据集的最好特征（划分之后信息熵最小，也就是信息增益最大的特征）\n",
    "            划分数据集\n",
    "            创建分支节点\n",
    "                for 每个划分的子集\n",
    "                    调用函数 createBranch （创建分支的函数）并增加返回结果到分支节点中\n",
    "            return 分支节点\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 决策树 开发流程\n",
    "1. 收集数据：可以使用任何方法。\n",
    "2. 准备数据：树构造算法只适用于标称型数据，因此数值型数据必须离散化。\n",
    "3. 分析数据：可以使用任何方法，构造树完成之后，我们应该检查图形是否符合预期。\n",
    "4. 训练算法：构造树的数据结构。\n",
    "5. 测试算法：使用经验树计算错误率。（经验树没有搜索到较好的资料，有兴趣的同学可以来补充）\n",
    "6. 使用算法：此步骤可以适用于任何监督学习算法，而使用决策树可以更好地理解数据的内在含义。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 决策树 特点\n",
    "- 优点：计算复杂度不高，输出结果易于理解，对中间值的缺失不敏感，可以处理不相关特征数据。\n",
    "- 缺点：可能会产生过度匹配问题。\n",
    "- 适用数据类型：数值型和标称型。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 示例一 鱼的分类"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 所有类别的香农信息熵\n",
    "$$H = - \\sum\\nolimits_{i=1}^nP(x_{i})\\log_{2}P(x_{i})$$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 程序清单3-1 计算给定数据的香农熵\n",
    "from math import log\n",
    "def calcShannonEnt(dataset):\n",
    "    # 求样本数\n",
    "    numEntries = len(dataset)\n",
    "    #计算标签label出现的此数\n",
    "    labelCounts = {}\n",
    "    for featVec in dataset:\n",
    "        #读训练集标签\n",
    "        currentLabel = featVec[-1]\n",
    "        #如果键值不存在，则创建\n",
    "        if currentLabel not in labelCounts.keys():\n",
    "            labelCounts[currentLabel] = 0\n",
    "        labelCounts[currentLabel] += 1\n",
    "    shannonEnt = 0.0\n",
    "    for key in labelCounts:\n",
    "        prob = float(labelCounts[key]/numEntries)\n",
    "        shannonEnt -= prob * log(prob, 2)\n",
    "    return shannonEnt\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "def createDataSet():\n",
    "    dataSet = [[1, 1, 'yes'],\n",
    "               [1, 1, 'yes'],\n",
    "               [1, 0, 'no'],\n",
    "               [0, 1, 'no'],\n",
    "               [0, 1, 'no']]\n",
    "    labels = ['no surfacing', 'flippers']\n",
    "    return dataSet, labels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "1.3709505944546687"
      ]
     },
     "execution_count": 29,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "myDat , labels = createDataSet()\n",
    "myDat\n",
    "calcShannonEnt(myDat)\n",
    "myDat[0][-1] = 'maybe'\n",
    "myDat\n",
    "calcShannonEnt(myDat)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [],
   "source": [
    "def splitDataSet(dataSet, axis, value):\n",
    "    \"\"\"\n",
    "    Desc:\n",
    "        把axis列值为value的数据集\n",
    "    Args:\n",
    "        dataSet 数据集\n",
    "        axis 列的索引\n",
    "        value 待分类的特征\n",
    "    return：\n",
    "        axis 列为value的数据集\n",
    "    \"\"\"\n",
    "    retDataSet = []\n",
    "    for featVec in dataSet:\n",
    "        if featVec[axis] == value:\n",
    "            reducedFeatVec = featVec[:axis]\n",
    "            reducedFeatVec.extend(featVec[axis+1:])\n",
    "            retDataSet.append(reducedFeatVec)\n",
    "    return retDataSet       \n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 45,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no']]\n",
      "['no surfacing', 'flippers']\n",
      "[[1, 'yes'], [1, 'yes'], [0, 'no']]\n",
      "[[1, 'no'], [1, 'no']]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "[1, 1, 1, 0, 0]"
      ]
     },
     "execution_count": 45,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# test splitDataSet\n",
    "myDat, labels = createDataSet()\n",
    "print(myDat)\n",
    "print(labels)\n",
    "#第0列为1的数据\n",
    "result1 = splitDataSet(myDat, 0, 1)\n",
    "print(result1)\n",
    "#第0列为0的数据\n",
    "result2 = splitDataSet(myDat, 0, 0)\n",
    "print(result2)\n",
    "len(myDat[0])\n",
    "[example[0] for example in myDat]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [],
   "source": [
    "def chooseBestFeatureToSplit(dataSet):\n",
    "    \"\"\"\n",
    "    Desc:\n",
    "        选择最好的特征\n",
    "    Args:\n",
    "        dataSet 数据集\n",
    "    returns：\n",
    "        bestFeature 最优的特之列\n",
    "    \"\"\"\n",
    "    # 第一行有多少列的 Feature, 最后一列是label\n",
    "    numFeatures = len(dataSet[0]) - 1\n",
    "    # 数据集的原始信息熵\n",
    "    baseEntropy = calcShannonEnt(dataSet)\n",
    "    # 最优的信息增益值, 和最优的Featurn编号\n",
    "    bestInfoGain, bestFeature = 0.0, -1\n",
    "    for i in range(numFeatures):\n",
    "        # 获取对应的feature下的所有数据\n",
    "        featList = [example[i] for example in dataSet]\n",
    "        #元素去重\n",
    "        uniqueVals = set(featList)\n",
    "        #创建临时信息熵\n",
    "        newEntropy = 0.0\n",
    "        for value in uniqueVals:\n",
    "            subDataSet = splitDataSet(dataSet, i, value)\n",
    "            #计算第i列，值为value的权重\n",
    "            prob = len(subDataSet)/float(len(dataSet))\n",
    "            ###########信息熵乘以权重，目的是样本数多的特征占比大#############\n",
    "            newEntropy += prob * calcShannonEnt(subDataSet)\n",
    "        infoGain = baseEntropy - newEntropy\n",
    "        print ('infoGain=', infoGain, 'bestFeature=', i, baseEntropy, newEntropy)\n",
    "        if (infoGain > bestInfoGain):\n",
    "            bestInfoGain = infoGain\n",
    "            bestFeature = i\n",
    "    return bestFeature\n",
    "        "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "infoGain= 0.4199730940219749 bestFeature= 0 0.9709505944546686 0.5509775004326937\n",
      "infoGain= 0.17095059445466854 bestFeature= 1 0.9709505944546686 0.8\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "0"
      ]
     },
     "execution_count": 50,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "chooseBestFeatureToSplit(myDat)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
